#
#
#{'DateTime': datetime.datetime(2008, 9, 11, 13, 31, 34),
# 'exif': {'EXIF ColorSpace': '1',
#          'EXIF ComponentsConfiguration': 'YCbCr',
#          'EXIF CompressedBitsPerPixel': '1',
#          'EXIF DateTimeDigitized': '2008:09:11 13:31:34',
#          'EXIF DateTimeOriginal': '2008:09:11 13:31:34',
#          'EXIF ExifImageLength': '2000',
#          'EXIF ExifImageWidth': '3008',
#          'EXIF ExifVersion': '0221',
#          'EXIF ExposureBiasValue': '2/3',
#          'EXIF ExposureProgram': 'Program Normal',
#          'EXIF ExposureTime': '1/160',
#          'EXIF FNumber': '63/10',
#          'EXIF FileSource': 'Digital Camera',
#          'EXIF Flash': 'No',
#          'EXIF FlashPixVersion': '0100',
#          'EXIF FocalLength': '18',
#          'EXIF InteroperabilityOffset': '29182',
#          'EXIF LightSource': '11',
#          'EXIF MaxApertureValue': '18/5',
#          'EXIF MeteringMode': '5',
#          'EXIF SceneType': 'Directly Photographed',
#          'EXIF SensingMethod': '2',
#          'EXIF SubSecTime': '80',
#          'EXIF SubSecTimeDigitized': '80',
#          'EXIF SubSecTimeOriginal': '80',
#          'EXIF UserComment': 'ASCII\x00\x00\x00                                    ',
#          'Image DateTime': '2008:09:11 13:31:34',
#          'Image ExifOffset': '216',
#          'Image Make': 'NIKON CORPORATION',
#          'Image Model': 'NIKON D70',
#          'Image Orientation': '1',
#          'Image ResolutionUnit': 'Pixels/Inch',
#          'Image Software': 'Ver.2.00 ',
#          'Image XResolution': '300',
#          'Image YCbCrPositioning': '2',
#          'Image YResolution': '300',
#          'Thumbnail Compression': 'JPEG Compressed',
#          'Thumbnail JPEGInterchangeFormat': '29320',
#          'Thumbnail JPEGInterchangeFormatLength': '8749',
#          'Thumbnail ResolutionUnit': 'Pixels/Inch',
#          'Thumbnail XResolution': '300',
#          'Thumbnail YCbCrPositioning': '2',
#          'Thumbnail YResolution': '300'},
# 'pil': {'ApertureValue': None,
#         'Artist': None,
#         'BatteryLevel': None,
#         'BitsPerSample': None,
#         'BrightnessValue': None,
#         'CFAPattern': '\x00\x02\x00\x02\x02\x01\x01\x00',
#         'CFARepeatPatternDim': None,
#         'ColorSpace': 1,
#         'ComponentsConfiguration': '\x01\x02\x03\x00',
#         'CompressedBitsPerPixel': (1, 1),
#         'Compression': None,
#         'Copyright': None,
#         'DateTime': '2008:09:11 13:31:34',
#         'DateTimeDigitized': '2008:09:11 13:31:34',
#         'DateTimeOriginal': '2008:09:11 13:31:34',
#         'ExifImageHeight': 2000,
#         'ExifImageWidth': 3008,
#         'ExifInteroperabilityOffset': 29182,
#         'ExifOffset': 216,
#         'ExifVersion': '0221',
#         'ExposureBiasValue': None,
#         'ExposureIndex': None,
#         'ExposureProgram': 2,
#         'ExposureTime': (10, 1600),
#         'FNumber': (63, 10),
#         'FileSource': '\x03',
#         'Flash': 0,
#         'FlashEnergy': None,
#         'FlashPixVersion': '0100',
#         'FocalLength': (180, 10),
#         'FocalPlaneResolutionUnit': None,
#         'FocalPlaneXResolution': None,
#         'FocalPlaneYResolution': None,
#         'GPSInfo': None,
#         'ISOSpeedRatings': None,
#         'ImageDescription': None,
#         'ImageHistory': None,
#         'ImageLength': None,
#         'ImageNumber': None,
#         'ImageWidth': None,
#         'InterColorProfile': None,
#         'Interlace': None,
#         'JpegIFByteCount': None,
#         'JpegIFOffset': None,
#         'LightSource': 11,
#         'Make': 'NIKON CORPORATION',
#         'MaxApertureValue': (36, 10),
#         'MeteringMode': 5,
#         'Model': 'NIKON D70',
#         'Noise': None,
#         'OECF': None,
#         'Orientation': 1,
#         'PhotometricInterpretation': None,
#         'PlanarConfiguration': None,
#         'PrimaryChromaticities': None,
#         'ReferenceBlackWhite': None,
#         'RelatedImageFileFormat': None,
#         'RelatedImageWidth': None,
#         'RelatedSoundFile': None,
#         'ResolutionUnit': 2,
#         'RowsPerStrip': None,
#         'SamplesPerPixel': None,
#         'SceneType': '\x01',
#         'SecurityClassification': None,
#         'SelfTimerMode': None,
#         'SensingMethod': 2,
#         'ShutterSpeedValue': None,
#         'Software': 'Ver.2.00 ',
#         'SpatialFrequencyResponse': None,
#         'SpectralSensitivity': None,
#         'StripByteConunts': None,
#         'StripOffsets': None,
#         'SubjectDistance': None,
#         'SubjectLocation': None,
#         'SubsecTime': '80',
#         'SubsecTimeDigitized': '80',
#         'SubsecTimeOriginal': '80',
#         'TIFF/EPStandardID': None,
#         'TimeZoneOffset': None,
#         'TransferFunction': None,
#         'WhitePoint': None,
#         'XResolution': (300, 1),
#         'YCbCrCoefficients': None,
#         'YCbCrPositioning': 2,
#         'YCbCrSubSampling': None,
#         'YResolution': (300, 1)}}

CHAR_ENCODING = 'ISO-8859-1'

from ceemtu.cetcore.models import *
from ceemtu.cetphoto.models import *

import os
import datetime

os.environ['DJANGO_SETTINGS_MODULE'] = 'ceemtu.settings'

class PhotoPatternMethods:
    
    def generate_photo_from_entry(self, pattern, _file_entry):
        "Creates a photo-entry based on a file-entry."
        metadata = _file_entry.get_metadata(flatten = True)

        ## iptc-caption/headline, xmp_title
        ##title = models.CharField(max_length=200)
        #description = models.TextField(null = True, blank = True)
        #notes = models.TextField(null = True, blank = True)
        #s = metadata.get('TITLE', metadata.get('generic extractor - Title'))
        #if type(s) == types.StringType:
        #    s = unicode(s, CHAR_ENCODING)
        #metadata['TITLE'] = s
        #
        #s = metadata.get('ARTIST', metadata.get('generic extractor - Author'))
        #if type(s) == types.StringType:
        #    s = unicode(s, CHAR_ENCODING)
        #metadata['ARTIST'] = s
        #
        #s = metadata.get('ALBUM', metadata.get('generic extractor - Album'))
        #if type(s) == types.StringType:
        #    s = unicode(s, CHAR_ENCODING)
        #metadata['ALBUM'] = s

        _title = _file_entry.filename

        try:
            v1,v2 = map(int, metadata.get('exif - EXIF FNumber').split('/'))
            _fnumber = float(v1) / float(v2)
        except:
            _fnumber = None
            
        try:
            _iso_speed = int(metadata.get('pil - ISOSpeedRatings'))
        except:
            _iso_speed = None
            
        try:
            v1,v2 = metadata.get('pil - ExposureTime')
            _exposure_time = float(v1)/float(v2)
        except:
            _exposure_time = None
            
        try:
            old_photo = Photo.objects.get(file_entry = _file_entry)[0]
            #old_photo.save()
        except:
            new_photo = Photo(
                title = _title,
                description = '',
                notes = '',
                file_entry = _file_entry,
                date_added = datetime.datetime.today(),
                date_of_creation = metadata.get('DateTime', datetime.datetime.today()),
                year = metadata.get('DateTime').year,
                month = metadata.get('DateTime').month,
                day = metadata.get('DateTime').day,
                rating = 0,
                shutter_speed = None,
                aperture = None,
                flash = metadata.get('exif - EXIF Flash', 'No') == 'Yes' and True or False,
                exposure_time = metadata.get('exif - EXIF ExposureTime'),
                camera_make = metadata.get('exif - Image Make'),
                camera_model = metadata.get('exif - Image Model'),
                fnumber = _fnumber,
                iso_speed = _iso_speed,
                orientation = metadata.get('exif - Image Orientation'),
                width = int(metadata.get('exif - EXIF ExifImageWidth', 0)),
                height = int(metadata.get('exif - EXIF ExifImageLength', 0)) 
            )
            new_photo.save()

            changed = False
            for period in DatePeriod.objects.all():
                if period.is_match(new_photo.date_of_creation):
                    new_photo.dateperiods.add(period)
                    changed = True

            if changed:
                new_photo.save()